﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SocanCode.Model
{
    /// <summary>
    /// 外键类
    /// </summary>
    public class ForeignKey
    {
        /// <summary>
        /// 从表
        /// </summary>
        public Table SlaveTable { get; set; }
        /// <summary>
        /// 主表
        /// </summary>
        public Table MasterTable { get; set; }
        /// <summary>
        /// 子表中的外键列（按数据库中定义的外键中列的顺序排列）
        /// </summary>
        public List<ForeignKeyColumn> ForeignKeyFields { get; set; }
        /// <summary>
        /// 关系的类型（一对一/一对多）
        /// </summary>
        public RelationType RelationType
        {
            get
            {
                //如果外键是从表的主键，就是一对一关系，否则是一对多关系
                bool isForeignKeyPrimaryKey = ForeignKeyFields.Select(a => a.LocalField).SequenceEqual(SlaveTable.PrimaryKey);
                return isForeignKeyPrimaryKey ? RelationType.OneToOne : RelationType.OneToMany;
            }
        }
        /// <summary>
        /// 当被参照记录被删除时采取的行动
        /// </summary>
        public ForeignKeyDeleteRule DeleteRule { get; set; }
    }

    /// <summary>
    /// 外键列
    /// </summary>
    public class ForeignKeyColumn
    {
        /// <summary>
        /// 本表中的列
        /// </summary>
        public Field LocalField { get; set; }
        /// <summary>
        /// 被参照的列
        /// </summary>
        public Field ReferencedField { get; set; }
        /// <summary>
        /// 列在外键中的位置
        /// </summary>
        public int Position { get; set; }
    }

    /// <summary>
    /// 关系类型
    /// </summary>
    public enum RelationType
    {
        /// <summary>
        /// 一对一关系
        /// </summary>
        OneToOne,
        /// <summary>
        /// 一对多关系
        /// </summary>
        OneToMany
    }
    /// <summary>
    /// 当被参照记录被删除时采取的行动
    /// </summary>
    public enum ForeignKeyDeleteRule
    {
        /// <summary>
        /// 不采取任何行动
        /// </summary>
        NoAction,
        /// <summary>
        /// 级联删除
        /// </summary>
        Cascade,
        /// <summary>
        /// 设为null
        /// </summary>
        SetNull,
    }
}
